﻿using AutoMapper;
using MediatR;
using PublicClass;
using PublicClass.Shift;
using S.Produce.Domains;
using S.Produce.Domains.DTO;
using S.Produce.Infrastructure;
using S.Produce.Read.Api.Application.Commands.ShiftCommands;

namespace S.Produce.Read.Api.Application.CommandHandlers.ShiftCommandHandlers
{
    /// <summary>
    /// 
    /// </summary>
    public class ShiftSelectCommandHandler : IRequestHandler<ShiftSelectCommand, PageInfo<ShiftDormDTO>>
    {
        private readonly IRepository<ShiftDorm> shiftdorm;
        private readonly IMapper mapper;

        public ShiftSelectCommandHandler(IRepository<ShiftDorm> shiftdorm, IMapper mapper)
        {
            this.shiftdorm = shiftdorm;
            this.mapper = mapper;
        }
        public async Task<PageInfo<ShiftDormDTO>> Handle(ShiftSelectCommand request, CancellationToken cancellationToken)
        {
            var info = shiftdorm.GetAllAsync().Result.AsQueryable().Where(x => x.IsDel == false);
            if (!string.IsNullOrEmpty(request.date))
            {
                var sdate = request.date.Split(",")[0];
                var edate = request.date.Split(",")[1];
                info = info.Where(x => x.TransferDate.Date >= DateTime.Parse(sdate) && x.TransferDate <= DateTime.Parse(edate));
            }
            if (!string.IsNullOrEmpty(request.Earbugles))
            {
                info = info.Where(x => x.Earbugles == request.Earbugles);
            }
            if (!string.IsNullOrEmpty(request.type))
            {
                info = info.Where(x => x.TransferType.ToString() == request.type);
            }
            if (!string.IsNullOrEmpty(request.OutBuildings))
            {
                info = info.Where(x => x.OriginallyDorm == request.OutBuildings);
            }
            if (!string.IsNullOrEmpty(request.OutColunm))
            {
                info = info.Where(x => x.OriginallyColumns == request.OutColunm);
            }
            if (!string.IsNullOrEmpty(request.InBuildings))
            {
                info = info.Where(x => x.DormName == request.InBuildings);
            }
            if (!string.IsNullOrEmpty(request.InColunm))
            {
                info = info.Where(x => x.ColumnsName == request.InColunm);
            }


            int totalCount = info.Count();
            int pageCount = (int)Math.Ceiling(totalCount * 1.0 / request.pageSize);
            info = info.OrderByDescending(x => x.CreateDate).Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize);
            var dto = new List<ShiftDormDTO>();
            var result = mapper.Map(info.ToList(), dto);
            var res = new PageInfo<ShiftDormDTO>()
            {
                datas = result,
                pageCount = pageCount,
                totalCount = totalCount
            };
            return res;
        }
    }
}
